package org.flyer.toolFrame.util;

import com.alibaba.fastjson.JSON;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public  class FileUtil {
    /**
     * 读取文件类容为字符串
     * @param inputStream
     * @return
     */
    public static String jsonRead(InputStream inputStream){
        DataInputStream dataInputStream = new DataInputStream(inputStream);

        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(dataInputStream, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {

        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return buffer.toString();
    }
    public static List<String> queryFiles(String location,String suffixs,List<String> fileLocations){
        File file=new File(location);
        String[] sufs = suffixs.split(",");
        if (file.isDirectory()) {
            File[] fileChildren = file.listFiles();
            for (File child:fileChildren) {
              if (child.isDirectory()){
                  //如果不是文件则 进入递归
                  queryFiles(child.getAbsolutePath(),suffixs,fileLocations);
              }else{
                  //是文件
                  //配置文件类型过滤
                  FileFilter fileFilter= pathname -> {
                      boolean flag=false;
                      for (String suf:sufs) {
                          if (pathname.toString().endsWith(suf)) {
                              flag = true;
                              break;
                          }
                      }
                      return flag;
                  };
                  //判断当前文件是否为所要的文件类型
                  if (fileFilter.accept(child)){//匹配成功 将结果加入列表中
                      fileLocations.add(child.getAbsolutePath());
                  }
              }
            }
        }else {
            return null;
        }
        return fileLocations;
    }
    public static Map<String,Object> getJsonMap(InputStream inputStream){
        return (Map<String,Object>) JSON.parse(jsonRead(inputStream));
    }

}
